/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */

package com.rest.client;

import android.os.Build;

import com.rest.converter.CommonInterceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import jz.joyoung.robot.util.LogUtil;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;


public class RestClient {
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private static final String TAG = "jy-" + RestClient.class.getSimpleName();

    private static final int DEFAULT_CONNECT_TIMEOUT = 10;
    private static final int DEFAULT_RW_TIMEOUT = 25;

    private OkHttpClient mOkHttpClient;
    public String token = "";

    private static class SingletonHolder {
        private static final RestClient INSTANCE = new RestClient();
    }

    /**
     * 获取单例
     */
    public static RestClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 因为设置了读写超时，该client不适用于上传和下载
     */
    private RestClient() {
        mOkHttpClient = new OkHttpClient.Builder()
                //log 拦截器
                .addNetworkInterceptor(new HttpLoggingInterceptor(message -> {
                    // android之json数据过长打印不全问题
                    if (message.length() > 4000) {
                        for (int i = 0; i < message.length(); i += 4000) {
                            if (i + 4000 < message.length()) {
                                LogUtil.d(TAG, message.substring(i, i + 4000));
                            } else {
                                LogUtil.d(TAG, message.substring(i));
                            }
                        }
                    } else {
                        LogUtil.d(TAG, message);
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder requestBuilder = original.newBuilder()
                            .addHeader("model", Build.MANUFACTURER + " " + Build.MODEL)
                            .addHeader("localsizeModel", "Android")
                            .addHeader("systemName", "Android " + Build.VERSION.RELEASE)
                            .addHeader("systemVersion", String.valueOf(Build.VERSION.SDK_INT))
                            .addHeader("Authorization", token)
                            .addHeader("mobileName", Build.MANUFACTURER)
                            .addHeader("appVersion", "4.2.2"); // Application.getAppVersionName()
                    // Request customization: add request headers
                    Response response = chain.proceed(requestBuilder.build());
                    return response;
                })
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_RW_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_RW_TIMEOUT, TimeUnit.SECONDS).cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public void clearSession() {
        cookieStore.clear();
    }
}
